import java.sql.*;
import java.io.*;

public
class DatabaseTest
{
	public static DatabaseTest databaseTest;
	protected Connection connection = null;
	protected static PrintWriter outp = null;
	public DatabaseTest(String fileName)
	{
		try{
			connect("test");
			writeRecords(fileName);
			close();
		}
		catch(SQLException e){
			outp.println("Bd: " + e);
			while((e = e.getNextException()) != null){
			}
		}
	}
	public static void setOutput()
	{
		try{
		outp = new PrintWriter(new OutputStreamWriter(System.out, "Cp852"), true);
		}
		catch(UnsupportedEncodingException e){
			System.out.println("Nie mona ustawi strony kodowej Cp852.");
			outp = new PrintWriter(new OutputStreamWriter(System.out), true);
		}
	}
	public static void main(String args[])
	{
		setOutput();
		if (args.length < 1){
			outp.println("Wywoanie programu: 'DatabaseTest nazwa_pliku'");
			System.exit(0);
		}
		databaseTest = new DatabaseTest(args[0]);
	}
	public void connect(String databaseName)
	throws SQLException
	{
		try{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		}
		catch(ClassNotFoundException e){
			outp.println("Bd przy adowaniu sterownika bazy: " + e);
			System.exit(-1);
		}
		connection = DriverManager.getConnection("jdbc:odbc:" + databaseName);
		outp.println("\nPoczenie nawizane!\n");
	}
	public void close()
	throws SQLException
	{
		connection.close();
		outp.println("\nPoczenie zamknite!\n");
	}
	public void writeRecords(String fileName)
	throws SQLException
	{
		PrintWriter fileStream = null;
		try{
		fileStream = new PrintWriter (new FileOutputStream(fileName), true);
		}
		catch(FileNotFoundException e){
			outp.println("Nie moge utworzy pliku: " + fileName);
			System.exit(-1);
		}		
		String query = "SELECT * FROM OSOBA";

		Statement statement = connection.createStatement();
		ResultSet rs = statement.executeQuery(query);
		while(rs.next()){
			String imie = rs.getString("IMIE");
			String nazwisko = rs.getString("NAZWISKO");
			String adres = rs.getString("ADRES");
			String telefon = rs. getString("TELEFON");
			String email = rs.getString("EMAIL");
			fileStream.println(
				imie + " " + 
				nazwisko + " " + 
				adres + " " + 
				telefon + " " +
				email);
		}
	}
}
